#pragma once

#include <iostream>
#include <pthread.h>
#include <vector>
#include <string>
#include <queue>
#include <unistd.h>

using namespace std;

struct ThreadInfo
{
    pthread_t tid;
    string name;
};

static const int defaultnum = 5;

template <class T>
class ThreadPool
{
public: // handlerTask函数内要调用，改成public
    // 封装加锁解锁
    void Lock()
    {
        pthread_mutex_lock(&mutex_);
    }
    void Unlock()
    {
        pthread_mutex_unlock(&mutex_);
    }

    void Wakeup()
    {
        pthread_cond_signal(&cond_);
    }
    void ThreadSleep()
    {
        pthread_cond_wait(&cond_, &mutex_);
    }

    bool IsQueueEmpty()
    {
        return tasks_.empty();
    }

    string GetThreadName(pthread_t tid)
    {
        for (const auto &ti : threads_)
        {
            if (ti.tid == tid)
                return ti.name;
        }
        return "None";
    }

public:
    ThreadPool(int num = defaultnum) : threads_(num)
    {
        pthread_mutex_init(&mutex_, nullptr);
        pthread_cond_init(&cond_, nullptr);
    }

    // void* HandlerTask(void* args)//在类内，第一个参数是类内指针this
    static void *HandlerTask(void *args) // 静态成员函数属于类，没有this指针
                                         // 无法直接访问成员函数和成员变量
    {
        ThreadPool<T> *tp = static_cast<ThreadPool<T> *>(args);
        string name = tp->GetThreadName(pthread_self());
        while (true)
        {
            tp->Lock();

            while (tp->IsQueueEmpty()) // 防止伪唤醒
            {
                tp->ThreadSleep();
            }
            T t = tp->Pop();

            tp->Unlock();

            // 拿走任务了就不用在锁内了
            t();
            cout << name << "run " << "result: " << t.GetResult() << endl;
        }
        return nullptr;
    }

    void Start()
    {
        int num = threads_.size();
        for (int i = 0; i < num; i++)
        {
            threads_[i].name = "thread-" + to_string(i + 1);
            pthread_create(&(threads_[i].tid), nullptr, HandlerTask, this); // 传递类对象的this指针
                                                                            // 方便handletask方法
        }
    }

    T Pop() // 不用加锁，自己保证在锁内环境执行
    {
        T t = tasks_.front();
        tasks_.pop();
        return t;
    }

    void Push(const T &t)
    {
        Lock();

        tasks_.push(t);
        Wakeup();

        Unlock();
    }

    ~ThreadPool()
    {
        pthread_mutex_destroy(&mutex_);
        pthread_cond_destroy(&cond_);
    }

private:
    vector<ThreadInfo> threads_; // 一批线程
    queue<T> tasks_;             // 任务队列

    pthread_mutex_t mutex_;
    pthread_cond_t cond_;
};